# Color by clone selective advantage

sweeps.to.plot <- c(1:1080)
pdf("growth-rates-of-clones.pdf",width=5,height=5)
for(swt in 1:length(sweeps.to.plot)){
  sw <- sweeps.to.plot[swt]
  # Load clones selective advantage, color clones by advantage
  clones.fitness <- read.csv(paste("../sim",sw,"/sim",sw,".clones",sep=""),header=FALSE)
  d <- read.csv(paste("../sim",sw,"/sim",sw,".frequencies",sep=""),header=FALSE)

# Remove duplicates
  clones.fitness <- unique(clones.fitness)

  cfit <- cbind(rep(0,nrow(clones.fitness)),rep(0,nrow(clones.fitness)))
  cfit[clones.fitness[,3]==1,2] <- "black"
  cfit[clones.fitness[,3]==2,2] <- "orange"
  cfit[clones.fitness[,3]==4,2] <- "red"
  cfit[clones.fitness[,3]==8,2] <- "brown"
  
# get clones that have reached more than 10% frequency over 20 years
# exclude the wild-type clone with clone_id=0
# exclude neutral clones
# clone_id, time, frequency
  dat <- d[d[,3]>0.10&d[,1]>0&d[,4]>104&d[,4]<110,]
# get the frequency of clones in dat, even if it dropped to 0 at some time points
  clones.freq <- d[d[,1] %in% dat[,1],]
  select.clones.fitness <- clones.fitness[clones.fitness[,1] %in% dat[,1],c(1,3)]
  all.s <- c(0.001,0.01,0.1,0.5,1,2)
  if(nrow(select.clones.fitness)>0){
    select.clones.fitness[select.clones.fitness[,2] %in% (1+all.s)^1,3] <- "magenta"
    select.clones.fitness[select.clones.fitness[,2] %in% (1+all.s)^2,3] <- "blue"
    select.clones.fitness[select.clones.fitness[,2] %in% (1+all.s)^3,3] <- "green"
    select.clones.fitness[select.clones.fitness[,2] %in% (1+all.s)^4,3] <- "orange"
    select.clones.fitness[select.clones.fitness[,2] %in% (1+all.s)^5,3] <- "red"    
  }
  x.max.gens <- max(d[,5]) 
  
# Plot
  plot(clones.freq[,5],clones.freq[,3],col="black",ylab="Frequency",xlab="Time (generations)",pch=NA,ylim=c(0,1.0),xlim=c(0,x.max.gens))
  rrr <- unique(clones.freq[,1])
  for(i in 1:length(rrr)){
    #lines(clones.freq[clones.freq[,1]==rrr[i],5]-min(clones.freq[clones.freq[,1]==rrr[i],5]),clones.freq[clones.freq[,1]==rrr[i],3])
    lines(clones.freq[clones.freq[,1]==rrr[i],5],clones.freq[clones.freq[,1]==rrr[i],3],col=select.clones.fitness[select.clones.fitness[,1]==rrr[i],3])
  }
  print (paste("sweep",sw,"done."))
}
dev.off()








